import { computed, defineComponent, onMounted, ref } from 'vue';
import Viewer from './viewer';
import { getModelList } from '@/api/model.api'
import { onReady } from '@dcloudio/uni-app';



export function useModel() {
  const modelList = ref([]);

  const index = ref(0)

  const model = computed(() => modelList.value[index.value]);

  const video = ref()

  const fetchModelList = async () => {
    const result = await getModelList()
    modelList.value = result || [];
    model.value = modelList.value[0] || {};
  }

  const prev = () => {
    const prevIndex = index.value - 1
    index.value = prevIndex < 0 ? modelList.value.length - 1 : prevIndex
    removeVideo();
  }

  const next = () => {
    
    const nextIndex = index.value + 1
    index.value = nextIndex >= modelList.value.length ? 0 : nextIndex;
    removeVideo()
  }


  const toggleVideo = (value) => {
    video.value = value
  }

  const removeVideo = () => {
    video.value = null
  }


  onMounted(() => {
    fetchModelList();
  })



  return {
    model,
    prev,
    next,
    video,
    toggleVideo,
    removeVideo
  }
}


export function useViewer() {

    const containerRef = ref<HTMLElement>();
    const viewer = ref<Viewer>();

    function toggleModel(model, mesh) {
      viewer.value?.loadModel(model, mesh)
    }

    function initViewer() {
      const canvas = uni.createCanvasContext('container')

      const threeViewer = new Viewer(canvas, {
        isDebug: true,
        hasAxes: true,
      });
      viewer.value = threeViewer;
    }
    onReady(() => {
      initViewer()
    })

    // onReady() {
    //   // 获取canvas上下文
    //   const query = uni.createSelectorQuery();
    //   query.select('#container').node().exec((res) => {
    //     const canvas = res[0].node;
    //     initViewer(canvas);
    //   });
    // };
    

    onMounted(() => {
      // initViewer();
    });

    return {
      containerRef,
      viewer,
      toggleModel
    };
    
}


export function useUser() {


  function login() {
    
    uni.login({
      provider: 'weixin',
      success: function (loginRes) {
        console.log(loginRes.authResult);
        // 获取用户信息
        uni.getUserInfo({
          provider: 'weixin',
          success: function (infoRes) {
            console.log('用户昵称为：' + infoRes.userInfo.nickName);
          }
        });
      }
    });
  }


  return {
    login
  }


}